470. 用 Rand7() 实现 Rand10()
为保证权益,题目请参考 470. 用 Rand7() 实现 Rand10()(From LeetCode).
解决方案1
Python
python
# 470. 用 Rand7() 实现 Rand10()
# https://leetcode-cn.com/problems/implement-rand10-using-rand7/
# The rand7() API is already defined for you.
# def rand7():
# @return a random integer in the range 1 to 7
import random
def rand7():
return random.randint(1, 7)
# class Solution:
# def rand10(self):
# """
# :rtype: int
# """
# t = (
# rand7()
# + rand7()
# + rand7()
# + rand7()
# + rand7()
# + rand7()
# + rand7()
# + rand7()
# + rand7()
# + rand7()
# ) % 10 + 1
# return t
# ! 拒绝选择
# class Solution:
# def rand10(self):
# """
# :rtype: int
# """
# x = (rand7() - 1) * 7 + rand7()
# while x > 40:
# x = (rand7() - 1) * 7 + rand7()
# return (x - 1) % 10 + 1
# 解决思路1
# class Solution:
# def rand10(self):
# """
# :rtype: int
# """
# x = rand7()
# while x > 5:
# x = rand7()
# y = rand7()
# while y == 7:
# y = rand7()
# y = y % 2
# z = x + y * 5
# return z
# 解决思路2
# The rand7() API is already defined for you.
# def rand7():
# @return a random integer in the range 1 to 7
class Solution:
def rand10(self):
t = 99
while t > 40:
t = (rand7() - 1) * 7 + rand7()
t = (t - 1) % 10 + 1
return t
if __name__ == "__main__":
solution = Solution()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83